package com.bm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bm.Do.Repair.RepairAllotDisposedDo;
import com.bm.Do.Common.InfoDo;
import com.bm.Do.Repair.RepairInfoDo;
import com.bm.Do.Repair.RepairMyListDo;
import com.bm.Vo.Repair.RepairAllotVo;
import com.bm.Vo.Repair.RepairDetailVo;
import com.bm.Vo.Repair.RepairListVo;
import com.bm.Vo.Repair.RepairMyDetailVo;
import com.bm.constant.Constants;
import com.bm.mapper.EjyyPropertyCompanyUserMapper;
import com.bm.mapper.EjyyRepairUrgeMapper;
import com.bm.mapper.EjyyWechatMpUserMapper;
import com.bm.model.EjyyPropertyCompanyUser;
import com.bm.model.EjyyRepair;
import com.bm.model.EjyyRepairUrge;
import com.bm.model.EjyyWechatMpUser;
import com.bm.query.Common.DetailQuery;
import com.bm.query.Repair.*;
import com.bm.service.EjyyRepairService;
import com.bm.mapper.EjyyRepairMapper;
import com.bm.util.DateUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.List;

/**
 *
 */
@Service
@Slf4j
public class EjyyRepairServiceImpl extends ServiceImpl<EjyyRepairMapper, EjyyRepair>
        implements EjyyRepairService {

    @Autowired
    private EjyyRepairMapper repairMapper;

    @Autowired
    private EjyyPropertyCompanyUserMapper propertyCompanyUserMapper;

    @Autowired
    private EjyyWechatMpUserMapper wechatMpUserMapper;

    @Autowired
    private EjyyRepairUrgeMapper repairUrgeMapper;

    /**
     * 分页查询全部
     *
     * @param repairListQuery
     * @return
     */
    @Override
    public PageInfo<RepairListVo> repairList(RepairListQuery repairListQuery) {
        //分页插件
        PageHelper.startPage(repairListQuery.getPageNum(), repairListQuery.getPageSize());

        List<RepairListVo> repairListVo = repairMapper.selectRepairByCommunityId(repairListQuery);

        PageInfo<RepairListVo> pageInfo = new PageInfo<>(repairListVo);
        return pageInfo;
    }

    /**
     * 新增工单
     *
     * @param repair
     * @return
     */
    @Transactional
    @Override
    public boolean createRepair(EjyyRepair repair) {
        repair.setPropertyCompanyUserId(repair.getWechatMpUserId() != null ? null : 1L);

//        repair.setRepairImgs();  放入图片暂时先不写
        //步骤
        repair.setStep(Constants.FITMENT_STEP);
        //时间
        repair.setCreatedAt(DateUtils.dateConversion());
        //调用sql查询
        int count = repairMapper.insert(repair);
        return count > 0;
    }

    /**
     * 工单详情
     *
     * @param detailQuery
     * @return
     */
    @Override
    public RepairDetailVo DetailRepair(DetailQuery detailQuery) {
        RepairDetailVo repairDetailVo = repairMapper.selectDetailById(detailQuery);
        if (repairDetailVo == null) {
            return null;
        }
        //创建分配员信息对象
        InfoDo allotInfo = new InfoDo();
        InfoDo disposedInfo = new InfoDo();

        //如果步骤在已经分配人员的话
        if (repairDetailVo.getStep() >= Constants.ALLOT_REPAIR_STEP) {
            //根据分配员id查询用户信息
            EjyyPropertyCompanyUser propertyCompanyUser = propertyCompanyUserMapper.selectById(repairDetailVo.getAllotUserId());
            allotInfo.setId(propertyCompanyUser.getId());
            allotInfo.setRealName(propertyCompanyUser.getRealName());
            //根据处理人id查询用户信息
            EjyyPropertyCompanyUser disposedUserInfo = propertyCompanyUserMapper.selectById(repairDetailVo.getDisposeUserId());
            disposedInfo.setId(disposedUserInfo.getId());
            disposedInfo.setRealName(disposedUserInfo.getRealName());
        }
        InfoDo referInfo = new InfoDo();
        if (repairDetailVo.getPropertyCompanyUserId() != null) {
            //根据公司用户id查询
            EjyyPropertyCompanyUser ejyyPropertyCompanyUser = propertyCompanyUserMapper.selectById(repairDetailVo.getPropertyCompanyUserId());
            referInfo.setId(ejyyPropertyCompanyUser.getId());
            referInfo.setRealName(ejyyPropertyCompanyUser.getRealName());
        } else {
            //否则根据微信用户id查询
            EjyyWechatMpUser wechatMpUser = wechatMpUserMapper.selectById(repairDetailVo.getWechatMpUserId());
            referInfo.setId(Integer.parseInt(wechatMpUser.getId() + ""));
            referInfo.setRealName(wechatMpUser.getRealName());
        }
        // 查询催促次数
        EjyyRepairUrge RepairUrge = repairUrgeMapper.selectById(detailQuery.getId());


        //清除部分数据 避免数据泄露
        repairDetailVo.setAllotUserId(null);
        repairDetailVo.setDisposeUserId(null);
        repairDetailVo.setPropertyCompanyUserId(null);
        repairDetailVo.setWechatMpUserId(null);
        //封装数据
        // 提出人信息
        repairDetailVo.setReferInfo(referInfo);
        //派遣人信息
        repairDetailVo.setAllotInfo(allotInfo);
        //处理人信息
        repairDetailVo.setDisposedInfo(disposedInfo);
        //催促信息
        repairDetailVo.setUrgeTotal(RepairUrge);

        return repairDetailVo;
    }

    /**
     * 查询工单
     *
     * @param repairAllotQuery
     * @return
     */
    @Override
    public RepairAllotVo repairAllot(RepairAllotQuery repairAllotQuery) {
        //创建条件
        LambdaQueryWrapper<EjyyRepair> lqw = new LambdaQueryWrapper<>();
        //构建条件
        lqw.eq(EjyyRepair::getId, repairAllotQuery.getId());
        lqw.eq(EjyyRepair::getCommunityId, repairAllotQuery.getCommunityId());
        lqw.eq(EjyyRepair::getStep, Constants.SUBMIT_REPAIR_STEP);
        //调用查询
        EjyyRepair detail = repairMapper.selectOne(lqw);
        if (ObjectUtils.isEmpty(detail)) {
            //非法维修工单
            return null;
        }

        log.info("",repairAllotQuery.getDisposeUserId());
        //查询处理人信息
        RepairAllotDisposedDo allotDisposedDo = repairMapper.selectDisPosedInfo(repairAllotQuery.getDisposeUserId());
        if (ObjectUtils.isEmpty(allotDisposedDo)) {
            //非法维修工单
            return null;
        }
        //如果没有人处理
        if(detail.getDisposeSubscribed()){
            EjyyWechatMpUser wechatMpUser = wechatMpUserMapper.selectById(detail.getWechatMpUserId());
            //需要封装小程序方面的代码进行进行推送信息
        }

        if(allotDisposedDo.getSubscribed() == 1 && allotDisposedDo.getOpenId() != null){
            //返回公众号方面的信息
            //进行公众号方面的信息推送
//            if (res.errcode !== 0) {
//                cwlog.error(`公众号推送${OA_NOTICE_TO_PROPERTY_COMPANY_USER}推送失败，${res.errmsg}`);
//            }
        }
        //处理到下一步
        detail.setStep(Constants.ALLOT_REPAIR_STEP);
        //调用sql
        detail.setAllotUserId(Constants.ADMIN_ID);
        //更新处理信息
        int count = repairMapper.update(detail, new LambdaQueryWrapper<EjyyRepair>().eq(EjyyRepair::getId, detail.getId()));
        allotDisposedDo.setOpenId(null);
        allotDisposedDo.setSubscribed(null);
        //创建vo对象 返回前端
        RepairAllotVo repairAllotVo = new RepairAllotVo();
        repairAllotVo.setAllotedAt(DateUtils.dateConversion());
        //根据id查询个管理员姓名
        EjyyPropertyCompanyUser companyUser = propertyCompanyUserMapper.selectById(Constants.ADMIN_ID);
        //创建信息对象
        InfoDo infoDo = new InfoDo();
        //封装数据
        infoDo.setId(Integer.parseInt(Constants.ADMIN_ID+""));
        infoDo.setRealName(companyUser.getRealName());
        //封装返回前端数据
        repairAllotVo.setAllotInfo(infoDo);
        return repairAllotVo;
    }


    /**
     * 确认维修
     * @param repairConfirmQuery
     * @return
     */
    @Override
    public Boolean repairConfirm(RepairConfirmQuery repairConfirmQuery) {
        //创建条件对象
        LambdaQueryWrapper<EjyyRepair> lqw = new LambdaQueryWrapper<>();
        //构建条件语句
        lqw.eq(EjyyRepair::getCommunityId,repairConfirmQuery.getCommunityId());
        lqw.eq(EjyyRepair::getId,repairConfirmQuery.getId());
        lqw.eq(EjyyRepair::getStep,Constants.ALLOT_REPAIR_STEP);
        //调用mapper查询
        EjyyRepair detail = repairMapper.selectOne(lqw);

        if(ObjectUtils.isEmpty(detail) || detail.getDisposeUserId() != Constants.ADMIN_ID){
            return false;
        }
        if(detail.getDisposeSubscribed()){
            //跳到指定页面 向小程序发送请求
            // repair Confirm 接口
        }
        //调用接口修改数据
        LambdaQueryWrapper<EjyyRepair> repairLqw = new LambdaQueryWrapper<>();
        lqw.eq(EjyyRepair::getId,detail.getId());
        //更新步骤
        detail.setStep(Constants.CONFIRM_REPAIR_STEP);
        //更新时间
        detail.setDisposedAt(DateUtils.dateConversion());

        int count = repairMapper.update(detail, lqw);


        return count > 0;
    }

    /**
     * 维修完成
     * @param repairFinishQuery
     * @return
     */
    @Override
    public Boolean repairFinish(RepairFinishQuery repairFinishQuery) {
        //创建条件对象
        LambdaQueryWrapper<EjyyRepair> lqw = new LambdaQueryWrapper<>();
        //构建条件
        lqw.eq(EjyyRepair::getId,repairFinishQuery.getId());
        lqw.eq(EjyyRepair::getCommunityId,repairFinishQuery.getCommunityId());
        lqw.eq(EjyyRepair::getStep,Constants.CONFIRM_REPAIR_STEP);
        //调用mapper查询
        EjyyRepair detail = repairMapper.selectOne(lqw);
        //目前暂定管理员id为1 写死的
        if(ObjectUtils.isEmpty(detail) || detail.getDisposeUserId() != Constants.ADMIN_ID){
            return false;
        }

        if(detail.getDisposeSubscribed()){
            //查询微信用户 然后向小程序端发出信息  暂定后面完成
        }
        StringBuilder imgSb = new StringBuilder();
        List<String> imgs = repairFinishQuery.getDisposeImgs();
        if(imgs.size() > 0){
            for (String img : imgs) {
                imgSb.append("#");
                imgSb.append(img);
            }
        }
        //放入图片
        detail.setDisposeImgs(imgSb.toString());
        //更新步骤
        detail.setStep(Constants.FINISH_REPAIR_STEP);
        //创建条件对象
        LambdaQueryWrapper<EjyyRepair> repairLqw = new LambdaQueryWrapper<>();
        //构建条件
        repairLqw.eq(EjyyRepair::getId,detail.getId());
        //调用mapper
        int count = repairMapper.update(detail, repairLqw);
        return count > 0;
    }

    /**
     * 合并工单选项
     * @param detailQuery
     * @return
     */
    @Override
    public List<EjyyRepair> repairMergeOption(DetailQuery detailQuery) {
        //创建条件对象
        LambdaQueryWrapper<EjyyRepair> lqw = new LambdaQueryWrapper<>();
        //构建条件
        lqw.eq(EjyyRepair::getId,detailQuery.getId());
        lqw.eq(EjyyRepair::getCommunityId,detailQuery.getCommunityId());
        lqw.eq(EjyyRepair::getStep,Constants.SUBMIT_REPAIR_STEP);
        //如果id为空
        lqw.isNull(EjyyRepair::getMergeId);
        //调用mapper查询
        EjyyRepair detail = repairMapper.selectOne(lqw);
        if(ObjectUtils.isEmpty(detail)){
            return null;
        }
        //创建条件对象 用来查询多组数据
        LambdaQueryWrapper<EjyyRepair> ListLqw = new LambdaQueryWrapper<>();
        ListLqw.eq(EjyyRepair::getCommunityId,detail.getCommunityId());
        ListLqw.eq(EjyyRepair::getId,detail.getId());
        ListLqw.eq(EjyyRepair::getStep,Constants.SUBMIT_REPAIR_STEP);
        //创建时间
//        ListLqw.lt(EjyyRepair::getCreatedAt,detail.getCreatedAt() - 1000 * 60 * 60 * 24);
//        ListLqw.gt(EjyyRepair::getCreatedAt,detail.getCreatedAt() + 1000 * 60 * 60 * 24);
        //  根据创建时间查找创建时间
        ListLqw.gt(EjyyRepair::getCreatedAt,detail.getCreatedAt() - 7);
        ListLqw.lt(EjyyRepair::getCreatedAt,detail.getCreatedAt() + 7);

        //调用mapper查询
        List<EjyyRepair> ejyyRepairs = repairMapper.selectList(ListLqw);

        return ejyyRepairs;
    }

    /**
     * 获取合并id
     * @param repairMergeQuery
     * @return
     */
    @Override
    public Long repairMerge(RepairMergeQuery repairMergeQuery) {
        //创建条件语句
        LambdaQueryWrapper<EjyyRepair> lqw = new LambdaQueryWrapper<>();
        //构建条件
        lqw.eq(EjyyRepair::getId,repairMergeQuery.getId());
        lqw.eq(EjyyRepair::getCommunityId,repairMergeQuery.getCommunityId());
        lqw.eq(EjyyRepair::getStep,Constants.SUBMIT_REPAIR_STEP);
        //调用mapper查询
        EjyyRepair detail = repairMapper.selectOne(lqw);
        if(ObjectUtils.isEmpty(detail)){
            return null;
        }
        //查询 然后 发送消息给小程序
        if(detail.getDisposeSubscribed()){
            //查询获得微信用户对象
            EjyyWechatMpUser ejyyWechatMpUser = wechatMpUserMapper.selectById(detail.getId());
            //发送数据给小程序端 和公众号
        }
        //更改detail里的mergeid
        detail.setMergeId(repairMergeQuery.getMergeId());
        //调用mapper更新数据
        repairMapper.update(detail,new LambdaQueryWrapper<EjyyRepair>().eq(EjyyRepair::getId,detail.getId()));
        //返回mergeId
        return repairMergeQuery.getMergeId();
    }

    /**
     * 查询维修的详情信息
     * @param detailQuery
     * @return
     */
    @Override
    public RepairMyDetailVo repairMyDetail(DetailQuery detailQuery) {
        RepairInfoDo info = repairMapper.selectRepairOnBuilding(detailQuery);
        //如果查询不到
        if(ObjectUtils.isEmpty(info)){
            return null;
        }
        //如果步骤大于2
        InfoDo allotInfo = new InfoDo();
        InfoDo disposedInfo = new InfoDo();
        if(info.getStep() >= Constants.ALLOT_REPAIR_STEP){
            //调用mapper查询
            EjyyPropertyCompanyUser companyUser = propertyCompanyUserMapper.selectById(info.getAllotUserId());
            allotInfo.setId(companyUser.getId());
            allotInfo.setRealName(companyUser.getRealName());
            //封装转让人信息
            disposedInfo.setId(companyUser.getId());
            disposedInfo.setRealName(companyUser.getRealName());
        }

        InfoDo referInfo = new InfoDo();
        //如果公司用户不为空就根据公司用户id查询
        if(info.getPropertyCompanyUserId() != null){
            //调用mapper查询
            EjyyPropertyCompanyUser companyUser = propertyCompanyUserMapper.selectById(info.getPropertyCompanyUserId());
            referInfo.setRealName(companyUser.getRealName());
            referInfo.setId(companyUser.getId());
        }else{
            //否则根据微信用户id查询
            //调用mapper查询
            EjyyWechatMpUser mpUser = wechatMpUserMapper.selectById(info.getWechatMpUserId());
            referInfo.setRealName(mpUser.getRealName());
            referInfo.setId(Integer.parseInt(mpUser.getId()+""));
        }
        info.setRefer(info.getPropertyCompanyUserId() == null ? "owner" : "colleague");
        //保护隐私将部分数据置为空
        info.setAllotUserId(null);
        info.setDisposeUserId(null);
        info.setPropertyCompanyUserId(null);
        info.setWechatMpUserId(null);

        //维修图片的list集合
        List<String> repairImgs = null;
        if(info.getRepairImgs() != null){
            //将字符串的图片以"#"分开
            repairImgs = Arrays.asList(info.getRepairImgs().split("#"));
        }
        //修理好后的图片
        List<String> disposeImgs = null;
        if(info.getDisposeImgs() != null){
            //将字符串的图片以"#"分开
            disposeImgs = Arrays.asList(info.getDisposeImgs().split("#"));
        }
        //将分开后的图片封装起来
        info.setRepairImages(repairImgs);
        info.setDisposeImages(disposeImgs);

        //创建需要对象返回
        RepairMyDetailVo repairMyDetailVo = new RepairMyDetailVo();

        //封装返回前端的数据  各个人的信息
        repairMyDetailVo.setAllotInfo(allotInfo);
        repairMyDetailVo.setDisposedInfo(disposedInfo);
        repairMyDetailVo.setReferInfo(referInfo);
        repairMyDetailVo.setRepairInfoDo(info);

        return repairMyDetailVo;
    }


    /**
     * 查询自己的维修记录
     * @param repairMyListQuery
     * @return
     */
    @Override
    public PageInfo<RepairMyListDo> repairMyList(RepairMyListQuery repairMyListQuery) {
        //mybatis分页插件
        PageHelper.startPage(repairMyListQuery.getPageNum(),repairMyListQuery.getPageSize());

        List<RepairMyListDo> repairMyListDo = repairMapper.selectRepairOnList(repairMyListQuery);
        //创建pageinfo对象将数据放入  mybatis分页插件
        PageInfo<RepairMyListDo> listDoPageInfo = new PageInfo<>(repairMyListDo);
        return listDoPageInfo;
    }
}
